package tech.xujian.easydb;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by Reder.Xu on 2016/11/18.
 */
public class DBHelper {


    private static String url;
    private static String password;
    private static String username;
    private static String driver = "com.mysql.jdbc.Driver";

    public static void init(String url,String password,String username){
        DBHelper.url = url;
        DBHelper.password = password;
        DBHelper.username = username;
    }


    public static void init(String url,String password,String username,String driver){
        DBHelper.url = url;
        DBHelper.password = password;
        DBHelper.username = username;
        DBHelper.driver = driver;
    }

    public Connection conn = null;
    public PreparedStatement pst = null;

    public DBHelper(){
        try {
            Class.forName(driver);//指定连接类型
            conn = DriverManager.getConnection(url, username, password);//获取连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public DBHelper(String sql) {
        try {
            Class.forName(driver);//指定连接类型
            conn = DriverManager.getConnection(url, username, password);//获取连接
            pst = conn.prepareStatement(sql);//准备执行语句
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if(conn != null)
                this.conn.close();
            if(pst != null)
                this.pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
